import 'package:erp_widget/src/components/widget/index.dart';
import 'package:erp_widget/src/theme/style.dart';
import 'package:flutter/material.dart';

/// github地址：https://github.com/weeidl/Custom_Bottom_Sheet
/// 自定义顶部内容
class DxCupertinoModalBottomSheet extends StatefulWidget {
  final Color backgroundColor;
  final Color pillColor;
  final String? title;
  final Widget child;

  const DxCupertinoModalBottomSheet({
    super.key,
    this.pillColor = DxStyle.gray4,
    this.backgroundColor = Colors.white,
    this.title,
    required this.child,
  });

  static show<T>({
    required BuildContext context,
    String? title,
    required Widget child,
    Color? barrierColor,
    bool barrierDismissible = true,
    Duration transitionDuration = const Duration(milliseconds: 300),
    Color pillColor = DxStyle.gray4,
    Color backgroundColor = Colors.white,
  }) {
    return showGeneralDialog(
      context: context,
      pageBuilder: (context, animation1, animation2) => child,
      barrierColor: barrierColor ?? Colors.black.withOpacity(0.5),
      barrierDismissible: barrierDismissible,
      barrierLabel: '关闭',
      transitionDuration: transitionDuration,
      transitionBuilder: (context, animation1, animation2, widget) {
        final curvedValue = Curves.easeInOut.transform(animation1.value) - 1.0;
        return Transform(
          transform: Matrix4.translationValues(0.0, curvedValue * -300, 0.0),
          child: Opacity(
            opacity: animation1.value,
            child: DxCupertinoModalBottomSheet(
              pillColor: pillColor,
              backgroundColor: backgroundColor,
              title: title,
              child: child,
            ),
          ),
        );
      },
    );
  }

  @override
  State<DxCupertinoModalBottomSheet> createState() => _DxCupertinoModalBottomSheetState();
}

class _DxCupertinoModalBottomSheetState extends State<DxCupertinoModalBottomSheet> {
  var _initialPosition = 0.0;
  var _currentPosition = 0.0;

  @override
  Widget build(BuildContext context) {
    final deviceWidth = MediaQuery.of(context).size.width;
    final deviceHeight = MediaQuery.of(context).size.height;

    return AnimatedPadding(
      padding: MediaQuery.of(context).viewInsets + EdgeInsets.only(top: deviceHeight / 3.0 + _currentPosition),
      duration: const Duration(milliseconds: 100),
      curve: Curves.decelerate,
      child: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: SizedBox(
          width: deviceWidth,
          height: deviceHeight / 1.5,
          child: Material(
            color: widget.backgroundColor,
            elevation: 24.0,
            type: MaterialType.card,
            shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.only(topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0)),
            ),
            child: Column(
              children: <Widget>[
                widget.title == null
                    ? SizedBox(
                        width: double.infinity,
                        child: Column(
                          children: <Widget>[
                            PillGesture(
                              pillColor: widget.pillColor,
                              onVerticalDragStart: _onVerticalDragStart,
                              onVerticalDragEnd: _onVerticalDragEnd,
                              onVerticalDragUpdate: _onVerticalDragUpdate,
                            )
                          ],
                        ),
                      )
                    : _titleWidget(),
                Expanded(
                  child: ScrollConfiguration(
                    behavior: DxNoScrollBehavior(),
                    child: SingleChildScrollView(physics: const BouncingScrollPhysics(), child: widget.child),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _titleWidget() {
    // 构建整体标题
    return Column(
      children: <Widget>[
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              child: Container(
                padding: const EdgeInsets.only(left: 20),
                alignment: Alignment.centerLeft,
                child: Text('关闭', style: DxStyle.$AAAAAA$12, textAlign: TextAlign.left),
              ),
              onTap: () => Navigator.of(context).pop(),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 12.0),
              child: Center(
                child: Text(widget.title!, textAlign: TextAlign.center, maxLines: 1, style: DxStyle.$404040$14$W500),
              ),
            ),
            const Padding(padding: EdgeInsets.only(right: 20), child: Text('  ')),
          ],
        ),
        //有标题则添加分割线
        const Divider(thickness: 1, height: 0.5, color: DxStyle.$F5F5F5),
      ],
    );
  }

  void _onVerticalDragStart(DragStartDetails drag) {
    setState(() => _initialPosition = drag.globalPosition.dy);
  }

  void _onVerticalDragUpdate(DragUpdateDetails drag) {
    setState(() {
      final temp = _currentPosition;
      _currentPosition = drag.globalPosition.dy - _initialPosition;
      if (_currentPosition < 0) {
        _currentPosition = temp;
      }
    });
  }

  void _onVerticalDragEnd(DragEndDetails drag) {
    if (_currentPosition > 100.0) {
      Navigator.pop(context);
      return;
    }
    setState(() {
      _currentPosition = 0.0;
    });
  }
}

class PillGesture extends StatelessWidget {
  final GestureDragStartCallback onVerticalDragStart;
  final GestureDragUpdateCallback onVerticalDragUpdate;
  final GestureDragEndCallback onVerticalDragEnd;
  final Color? pillColor;

  const PillGesture({
    super.key,
    required this.onVerticalDragStart,
    required this.onVerticalDragUpdate,
    required this.onVerticalDragEnd,
    required this.pillColor,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onVerticalDragStart: onVerticalDragStart,
      onVerticalDragUpdate: onVerticalDragUpdate,
      onVerticalDragEnd: onVerticalDragEnd,
      child: Container(
        margin: const EdgeInsets.only(top: 10, bottom: 20),
        height: 5.0,
        width: 25.0,
        decoration: BoxDecoration(
          color: pillColor ?? Colors.blueGrey[200],
          borderRadius: BorderRadius.circular(50.0),
        ),
      ),
    );
  }
}
